package com.example.springbootv1.controller;
import com.example.springbootv1.pojo.PojoTest;
import com.example.springbootv1.service.PojoTestService;
import com.example.springbootv1.util.Result;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController  // 保证返回的是JSON数据 不能直接用@Controller，或者是在每个请求前面加上@ResponseBody
@RequestMapping("/pojoTest")
@CrossOrigin(origins = "*")  // 开放所有域，非GET请求会有安全问题
public class PojoTestController {
    @Autowired
    private PojoTestService pojoTestService;

    /**
     * 查询列表
     * @return Result
     */
    @GetMapping("/list")
    public Result getList() {
        return Result.success(pojoTestService.getList());
    }

    /**
     * 从URL中获取参数需要 @PathVariable
     * @param id id
     * @return Result
     */
    @GetMapping("/getById/{id}")
    public Result getById(@PathVariable Long id) {
        return Result.success(pojoTestService.queryById(id));
    }

    /**
     * 新增  从前端获取对象，需要@RequestBody
     * @return Result
     */
    @PostMapping("/add")
    public Result add(@RequestBody PojoTest pojoTest) {
        return Result.success(pojoTestService.insert(pojoTest));
    }

    /**
     * 更新数据
     * @param  pojoTest 对象
     * @return Result
     */
    @PutMapping("/update")
    public Result update(@RequestBody PojoTest pojoTest) {
        return Result.success(pojoTestService.update(pojoTest));
    }

    /**
     * 删除日志
     * @param id ID
     * @return Result
     */
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Long id) {
        return Result.success(pojoTestService.deleteById(id));
    }

    /**
     * 登录验证    多个参数传递到XML里面的方法
     * @param name  登录名
     * @param charType  登录方法
     * @return 日志对象
     */
    @PostMapping("/login")
    public Result login(@RequestParam(value = "name", required = false) String name,
                        @RequestParam(value = "charType", required = false) String charType) {
        System.out.println("--------"+name+"-------------");
        System.out.println("--------"+charType+"-------------");
        PojoTest pojoTest = pojoTestService.login(name, charType);
        if (pojoTest != null) {
            return Result.success(pojoTest);
        } else {
            return Result.error("登录失败！");
        }

    }

    /**
     * 分页查询
     * @param pojoTest 对象
     * 前端传回来：当前页和每页显示记录数
     * mapper层需要啥：
     * 1. 从第几条开始查
     * 2. 每页显示的记录数 （当前页-1）*每页显示的记录数
     * @return Result
     * @serialData 对象列表
     */
    @GetMapping("/fenYeList")
    public Result getLoginLogByFenYe(PojoTest pojoTest) {
        int fromIndex = (pojoTest.getCurrentIndex() - 1) * pojoTest.getPageSize();
        pojoTest.setFromIndex(fromIndex);
        Map<String , Object> map = new HashMap<String, Object>();
        map.put("pojoTestList", pojoTestService.getByFenYe(pojoTest));
        map.put("totalCount", pojoTestService.getByFenYeCount(pojoTest));
        return Result.success(map);
    }

    @GetMapping("/fenYeCount")
    public Result getByFenYeCount(PojoTest pojoTest) {
        return Result.success(pojoTestService.getByFenYeCount(pojoTest));
    }

    /**
     * 搜索，模糊匹配
     * @param pojoTest
     * @return
     */
    @GetMapping("/search")
    public Result getObjByObj(PojoTest pojoTest) {
        List<PojoTest> search = pojoTestService.getObjByObj(pojoTest);
        if (!search.isEmpty()) {
            return Result.success(search);
        } else {
            return Result.error("没查到！");
        }

    }

    @DeleteMapping("/deleteBatch/{ids}")
    public Result deleteBatch(@PathVariable List<Long> ids) {
        int count = pojoTestService.deleteBatch(ids);
        if (count > 0) {
            return Result.success(count);
        } else {
            return Result.error("删除失败！");
        }
    }

    /**
     * 导出Excel表格
     * @return
     */
    @GetMapping("/exportEquipmentExcel")
    public void exportEquipmentExcel(HttpServletResponse response) throws IOException {
        try{
            String[] colHeadName={"登录时间","登录姓名","登录方法","登录等级"};
            List<PojoTest> loginLogList = pojoTestService.getList();
            List<Object[]> listObject=new ArrayList<Object[]>();
            // 定义输入格式（匹配原始字符串）
            SimpleDateFormat inputFormat = new SimpleDateFormat(
                    "EEE MMM dd HH:mm:ss zzz yyyy", Locale.ENGLISH
            );

            // 解析字符串为Date对象


            for(int i=0;i<loginLogList.size();i++){
                Date date = loginLogList.get(i).getDateTime();
                // 定义输出格式
                SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
                outputFormat.setTimeZone(TimeZone.getTimeZone("GMT+8"));
                // 格式化日期并输出
                String formattedDate = outputFormat.format(date);
                listObject.add(new Object[]{
                        formattedDate,
                        loginLogList.get(i).getName(),
                        loginLogList.get(i).getCharType(),
                        loginLogList.get(i).getDoubleType()
                });
            }
            pojoTestService.exportJobLevelExcel(colHeadName,listObject,response);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @PostMapping("/importEquipmentExcel")
    public void importEquipmentExcel() {
        // 该实现导入EXCEL啦！

    }


}
